package com.ztgf.commodity.api.client;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.commodity.api.common.SysLogs;
import com.ztgf.commodity.models.bo.*;
import com.ztgf.commodity.models.dto.CommodityAuditLogDTO;
import com.ztgf.commodity.models.service.ICommodityAuditLogService;
import com.ztgf.commodity.models.service.ICommodityComboRelationService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.service.ICommodityParamValueRelationService;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.ExcelExport2;
import com.ztgf.common.utils.StrUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * author: chenyu.wang
 * date: 2020-05-25 16:35
 * Description:
 */
@RestController
@RequestMapping("/api/commodityInfo")
@Slf4j
@Api(value = "CommodityInfoApiController", tags = "商品表api接口")
public class CommodityInfoApiController {

    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @DubboReference
    private ICommodityParamValueRelationService commodityParamValueRelationService;
    @DubboReference
    private ICommodityComboRelationService commodityComboRelationService;
    @DubboReference
    private ICommodityAuditLogService auditLogService;

    /**
     * 根据卖家店铺id查询热销
     *
     * @param shopId 卖家店铺id
     * @return
     */
    @PostMapping("/getShopHotSell")
    @ApiOperation(value = "获取热销", notes = "获取热销")
    public Result getShopHotSell(Long shopId) {
        List<CommodityInfoHotSellVO> shopHotSell = commodityInfoService.getShopHotSell(shopId);
        return new Result<>(shopHotSell);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改商品", notes = "修改商品")
    public Result updateCommodityInfo(CommodityReleaseBO bo) {
        return commodityInfoService.update(bo);
    }

    @PostMapping("/updateStatus")
    @ApiOperation(value = "商品上架下架", notes = "商品上架下架")
    @ApiImplicitParam(name = "id", value = "商品表id", required = true, paramType = "query", dataType = "Long")
    public Result updateStatus(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
//        return commodityInfoService.updateStatus(id);
        return commodityInfoService.commodityOnAndOffShelves(id);
    }

    @PostMapping("/deleteLogic")
    @ApiOperation(value = "删除/恢复商品表(逻辑删除)", notes = "删除/恢复商品表(逻辑删除)")
    @ApiImplicitParam(name = "id", value = "商品表id", required = true, paramType = "query", dataType = "Long")
    public Result deleteLogic(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        return commodityInfoService.deleteLogic(id);

    }

    @PostMapping(value = "/saveReleaseCommodity")
    @ApiOperation(value = "保存发布商品", notes = "保存发布商品")
    public Result saveReleaseCommodity(CommodityReleaseBO saveBO) {
        Result<List<String>> listResult = commodityInfoService.saveReleaseCommodity (saveBO);
        if (listResult.getCode () == 0){
            List<String> data = listResult.getData ();
            for (String commodityIdStr: data) {
                Long commodityId = Long.parseLong (commodityIdStr);
                CommodityRegardVO vo = commodityInfoService.queryAdminCenterGoodsDetails(commodityId);
                String params = JSON.toJSONString (vo);
                Wrapper<CommodityAuditLogDTO> wrapper = new EntityWrapper<> ();
                wrapper.eq("commodity_id", commodityId);
                wrapper.orderBy ("create_time",false);
                List<CommodityAuditLogDTO> commodityAuditLogDTOS = auditLogService.selectList (wrapper);
                if (CustomizeUtil.listIsNotNull (commodityAuditLogDTOS)){
                    commodityAuditLogDTOS.get (0).setParams (params);
                    auditLogService.updateById (commodityAuditLogDTOS.get (0));
                }
            }
        }

        return listResult;
    }

    @PostMapping("/querySellerAllGoodsPageList")
    @ApiOperation(value = "卖家端产品管理全部产品列表", notes = "卖家端产品管理全部产品列表")
    public Result querySellerPageList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> list = commodityInfoService.querySellerPageList(sellerVO);
        return new Result<>(list);
    }

    @PostMapping("/querySellerReviewList")
    @ApiOperation(value = "卖家端产品审核中产品列表", notes = "卖家端产品审核中产品列表")
    public Result querySellerReviewList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> page = commodityInfoService.querySellerReviewList(sellerVO);
        return new Result<>(page);
    }

    @PostMapping("/querySellerNotOnGoodsList")
    @ApiOperation(value = "卖家个人中心未上架产品列表", notes = "卖家个人中心未上架产品列表")
    public Result querySellerNotOnGoodsList(CommoditySellerVO sellerVO) {
        Page<CommoditySellerVO> page = commodityInfoService.querySellerNotOnGoodsList(sellerVO);
        return new Result<>(page);
    }

    @PostMapping("/querySellerInPutawayList")
    @ApiOperation(value = "卖家中心上架中的产品列表", notes = "卖家中心上架中的产品列表")
    public Result querySellerInPutawayList(CommodityInPutawayBO sellerVO) {
        Page<CommodityInPutawayVO> page = commodityInfoService.querySellerInPutawayList(sellerVO);
        return new Result<>(page);
    }

    @PostMapping("/querySellerInventoryList")
    @ApiOperation(value = "卖家中心产品库存管理列表", notes = "卖家中心产品库存管理列表")
    public Result querySellerInventoryList(CommodityInventoryBO sellerVO) {
        Page<CommodityInventoryVO> page = commodityInfoService.querySellerInventoryList(sellerVO);
        return new Result<>(page);
    }

    @PostMapping("/deletePhysical")
    @ApiOperation(value = "彻底删除商品(物理删除)", notes = "彻底删除商品(物理删除)")
    @ApiImplicitParam(name = "id", value = "商品表id", required = true, paramType = "query", dataType = "Long")
    public Result deletePhysical(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        return commodityInfoService.deletePhysical(id);
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除商品表表", notes = "批量删除商品表")
    @ApiImplicitParam(name = "ids", value = "ids:以逗号隔开", required = true, paramType = "query", dataType = "String")
    public Result deleteBatch(String ids) {
        if (StrUtils.isEmpty(ids)) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            return commodityInfoService.deleteBatchPhysical(ids);
        }
    }

    @PostMapping(value = "/getCountSales")
    @ApiOperation(value = "销量统计", notes = "销量统计")
    public Result getCountSales(Long id,Long shopId) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        Integer sales = commodityInfoService.getCountSales(id,shopId);
        return new Result<>(sales);
    }

    @SysLogs(value = "查看商品详情")
    @PostMapping(value = "/getCommodityDetails")
    @ApiOperation(value = "商城商品基础详细信息", notes = "商城商品基础详细信息")
    public Result getCommodityDetails(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        CommodityDetailsVO details = commodityInfoService.getCommodityDetails(id);
        return new Result<>(details);
    }

    @PostMapping(value = "/getSimilarCommodity")
    @ApiOperation(value = "商品商品详情同类商品推荐", notes = "商品商品详情同类商品推荐")
    public Result getSimilarCommodity(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        List<CommoditySimilarVO> page = commodityInfoService.getSimilarCommodity(id);
        return new Result<>(page);
    }

    @PostMapping(value = "/querySellerRecycleBinList")
    @ApiOperation(value = "卖家个人中心商品回收站列表", notes = "卖家个人中心商品回收站列表")
    public Result querySellerRecycleBinList(CommodityRecycleBinBO bo) {
        Page<CommodityRecycleBinVO> page = commodityInfoService.querySellerRecycleBinList(bo);
        return new Result<>(page);
    }

    @PostMapping(value = "/updateBatchStatus")
    @ApiOperation(value = "批量逻辑删除/恢复商品", notes = "批量逻辑删除/恢复商品")
    public Result updateBatchStatus(String ids, Integer type) {
        if (!StringUtils.isNotBlank(ids)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        //type为0是批量删除，否则批量恢复
        if (type.equals(0)) {
            return commodityInfoService.deleteLogicBatch(ids);
        } else {
            return commodityInfoService.updateBatchRestore(ids);
        }
    }

    @PostMapping(value = "/updateBatchUpOrDownFrame")
    @ApiOperation(value = "批量上架/下架商品", notes = "批量上架/下架商品")
    public Result updateBatchUpOrDownFrame(String ids, Integer type) {
        //type为0是批量上架，否则批量下架
        if (type.equals(0)) {
            return commodityInfoService.updateBatchUpFrame(ids);
        } else {
            return commodityInfoService.updateBatchDownFrame(ids);
        }
    }

    @PostMapping(value = "/queryGoodsParamDetails")
    @ApiOperation(value = "根据商品id获取商品参数信息详情,用于商品详情页", notes = "根据商品id获取商品参数信息详情,用于商品详情页")
    public Result queryGoodsParamDetails(Long id) {
        if (id != null) {
            List<CommodityParamValueRelationVO> list = commodityParamValueRelationService.queryGoodsParamDetails(id);
            return new Result<>(list);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @PostMapping(value = "/queryGoodsComboMsg")
    @ApiOperation(value = "根据商品id，查询商品套餐情况", notes = "根据商品id，查询商品套餐情况")
    public Result queryGoodsComboMsg(Long id) {
        if (id != null) {
            List<CommodityComboRelationVO> list = commodityInfoService.queryGoodsComboMsg(id);
            return new Result<>(list);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @PostMapping(value = "/getByGoodsIdAndComboId")
    @ApiOperation(value = "根据商品id和套餐表id获取商品套餐价格信息", notes = "根据商品id和套餐表id获取商品套餐价格信息")
    public Result getByGoodsIdAndComboId(Long goodsId, Long comboId) {
        if (goodsId != null && comboId != null) {
            CommodityComboRelationVO dto = commodityComboRelationService.getByGoodsIdAndComboId(goodsId, comboId);
            return new Result<>(dto);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }


    @PostMapping(value = "/queryCenterGoodsDetails")
    @ApiOperation(value = "查看产品详情", notes = "查看产品详情")
    public Result queryCenterGoodsDetails(Long id) {
        if (id != null) {
            CommodityRegardVO vo = commodityInfoService.queryCenterGoodsDetails(id);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }


    @PostMapping(value = "/queryShopCommodityList")
    @ApiOperation(value = "查询店铺下商品，用于商城店铺装修页", notes = "查询店铺下商品，用于商城店铺装修页")
    public Result queryShopCommodityList(CommodityDecorationBO bo) {
        if (bo.getShopId() != null) {
            return new Result<>(commodityInfoService.queryShopCommodityList(bo));
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @PostMapping(value = "/queryShopAllCommodityList")
    @ApiOperation(value = "查询商城店铺所有商品,店铺所有产品页面", notes = "查询商城店铺所有商品,店铺所有产品页面")
    public Result queryShopAllCommodityList(CommodityShopAllListBO bo) {
        if (bo.getShopId() != null) {
            return new Result<>(commodityInfoService.queryShopAllCommodityList(bo));
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @SysLogs(value = "查看商城商品详情页")
    @PostMapping(value = "/queryCommodityDetailsPageData")
    @ApiOperation(value = "商城商品详情页", notes = "商城商品详情页")
    public Result queryCommodityDetailsPageData(Long id) {
        if (id != null) {
            CommodityDetailsPageVO vo = commodityInfoService.queryCommodityDetailsPageData(id);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @GetMapping(value = "/batchExportGoodsList/{ids}")
    @ApiOperation(value = "批量导出商品", notes = "批量导出商品")
    public void batchExportGoodsList(HttpServletResponse response, @PathVariable String ids) {
        //创建一个数组用于设置表头
        String[] attributeNames = new String[]{"商品编号", "商品名称", "规格型号", "价格", "库存剩余"};
        // 查询商品
        List<GoodsExportVO> list = commodityInfoService.getExportSku(ids);
        ExcelExport2.export(response, list, attributeNames, "_产品");
    }

    @PostMapping(value = "/getGoodsAllAttrs")
    @ApiOperation(value = "获取商品所拥有的规格属性", notes = "获取商品所拥有的规格属性")
    public Result getGoodsAllAttrs(Long id) {
        if (id != null) {
            List<CommoditySKUVO> goodsSku = commodityInfoService.getGoodsSku(id);
            return new Result<>(goodsSku);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }


    @PostMapping(value = "/getGoodsCompare")
    @ApiOperation(value = "同类目下商品价格比较", notes = "同类目下商品价格比较")
    public Result getGoodsCompare(Long category) {
        if (category != null) {
            String real = commodityInfoService.getGoodsCompare(category);
            return new Result<>(real);
        }
        return new Result<>(CodeEnum.FAIL_100002);
    }

    @PostMapping("/updateGoodsBack")
    @ApiOperation(value = "打回修改商品", notes = "打回修改商品")
    public Result updateGoodsBack(CommodityReleaseBO bo) {
        Result result = commodityInfoService.updateGoodsBack (bo);
        if (result.getCode () == 0){
            CommodityRegardVO vo = commodityInfoService.queryAdminCenterGoodsDetails(bo.getId ());
            String params = JSON.toJSONString (vo);
            Wrapper<CommodityAuditLogDTO> wrapper = new EntityWrapper<> ();
            wrapper.eq("commodity_id", bo.getId ());
            wrapper.orderBy ("create_time",false);
            List<CommodityAuditLogDTO> commodityAuditLogDTOS = auditLogService.selectList (wrapper);
            if (CustomizeUtil.listIsNotNull (commodityAuditLogDTOS)){
                commodityAuditLogDTOS.get (0).setParams (params);
                auditLogService.updateById (commodityAuditLogDTOS.get (0));
            }
        }
        return result;
    }

    @PostMapping("/updateLogImg")
    @ApiOperation(value = "商品主图处理", notes = "商品主图处理")
    public Result updateLogImg() {
        commodityInfoService.updateLogImg();
        return new Result<>();
    }
}
